package com.jeeplus.modules.web.wx;

import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.bean.request.WxPaySendRedpackRequest;
import com.github.binarywang.wxpay.bean.result.WxPaySendRedpackResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Lists;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.web.entity.WxGoods;
import com.jeeplus.modules.web.entity.WxGoodsRecord;
import com.jeeplus.modules.web.entity.WxUser;
import com.jeeplus.modules.web.entity.WxUserIntegrationRecord;
import com.jeeplus.modules.web.entity.wx.YsUser;
import com.jeeplus.modules.web.mapper.*;
import com.jeeplus.modules.web.service.WxGoodsRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by rongj on 2017/9/4.
 */
@Controller
@RequestMapping(value = "/wx/goods")
public class YjGoodsController extends BaseController {

    @Autowired
    WxGoodsMapper wxGoodsMapper;
    @Autowired
    WxUserMapper wxUserMapper;
    @Autowired
    WxUserWalletMapper wxUserWalletMapper;
    @Autowired
    WxUserIntegrationRecordMapper wxUserIntegrationRecordMapper;
    @Autowired
    WxUserCouponMapper wxUserCouponMapper;
    @Autowired
    private WxGoodsRecordMapper wxGoodsRecordMapper;
    @Autowired
    private WxGoodsRecordService wxGoodsRecordService;
    @Autowired
    private WxPayService payService;

    /**
     * 转盘页面
     *
     * @return
     */
    @RequestMapping("/home")
    @ResponseBody
    public Map<String, Object> get_openId(String token, HttpServletRequest request) throws ParseException {
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);

        Map<String, Object> map = new HashMap<String, Object>();
        //钱包信息
        map.put("userWallet", wxUserWalletMapper.getUserWallet(wxUserInfo.getId()));
        long time = Achieve.getDayBegin();
        map.put("integrationTime", wxGoodsMapper.getIntegrationTime(new Timestamp(time),
                new Timestamp(time + ((1000l * 60 * 60 * 24) - 10000)), wxUserInfo.getId()));
        List<WxGoods> wxGoodsList = wxGoodsMapper.findList(new WxGoods());

        int i = 0;
        for (WxGoods wxGoods : wxGoodsList) {
            wxGoods.setIndex(i);
            wxGoods.setName(wxGoods.getGoodsName());
            i++;
        }
        map.put("goodsList", wxGoodsList);
        WxUserIntegrationRecord wxUserIntegrationRecord = new WxUserIntegrationRecord();
        WxUser wxUser = new WxUser();
        wxUser.setId(wxUserInfo.getId());
        wxUserIntegrationRecord.setUser(wxUser);
        map.put("wxUserIntegrationRecordList", wxUserIntegrationRecordMapper.findList(wxUserIntegrationRecord));
        return map;
    }

    /**
     * 转盘页面
     *
     * @return
     */
    @RequestMapping("/addGoods")
    @ResponseBody
    public synchronized Map<String, Object> addGoods(String token, HttpServletRequest request) throws ParseException {
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 1);
        map.put("data", "抽奖已停止,敬请期待新系统上线");
//        List<String> list = wxGoodsMapper.getIdList();
//        long time = Achieve.getDayBegin();
//        int i = wxGoodsMapper.getIntegrationTime(new Timestamp(time),
//                new Timestamp(time + ((1000l * 60 * 60 * 24) - 10000)), wxUserInfo.getId());
//        System.out.println(i);
//        WxUserIntegrationRecord wxUserIntegrationRecord = new WxUserIntegrationRecord();
//        WxUser wxUser = new WxUser();
//        wxUser.setId(wxUserInfo.getId());
//        wxUserIntegrationRecord.setUser(wxUser);
//        wxUserIntegrationRecord.setType(1);
//        if (i == 0) {
//            wxUserIntegrationRecord.setText("每日免费抽奖");
//            wxUserIntegrationRecord.setIntegration("0");
//        } else {
//            //收费
//            int s = wxUserWalletMapper.setIntegration(wxUserInfo.getId(), 20);
//            if (s != 1) {
//                map.put("code", 1);
//                map.put("data", "积分不足");
//                return map;
//            }
//            wxUserIntegrationRecord.setText("抽奖消费");
//            wxUserIntegrationRecord.setIntegration("20");
//        }
//        wxGoodsMapper.addTime(wxUser.getId());
//        wxUserIntegrationRecordMapper.insert(wxUserIntegrationRecord);
//
//        String number = getNumber(list);
//        WxGoods wxGoods = wxGoodsMapper.get(number);
//        //查看奖品类型
//        int type = wxGoods.getType();
//        //这里减去积分
//        String integration = wxGoods.getIntegration();
//        WxUserIntegrationRecord wxUserIntegrationRecords = new WxUserIntegrationRecord();
//        wxUserIntegrationRecords.setUser(wxUser);
//        wxUserIntegrationRecords.setType(0);
//        wxUserIntegrationRecords.setText(wxGoods.getGoodsName());
//        if (type == 1) {
//            //积分商品
//            //增加积分
//            wxUserIntegrationRecords.setIntegration(integration);
//            wxUserWalletMapper.setAddIntegration(wxUserInfo.getId(), Integer.valueOf(integration));
//
//            //积分多少
//        } else {
//            //非积分商品
//            wxUserIntegrationRecords.setIntegration("0");
//            WxUserCoupon wxUserCoupon = new WxUserCoupon();
//            wxUserCoupon.setUser(wxUser);
//            wxUserCoupon.setCouponType(wxGoods.getCoupon());
//            wxUserCoupon.setWay("来源于抽奖");
//            wxUserCouponMapper.insert(wxUserCoupon);
//        }
//        wxUserIntegrationRecordMapper.insert(wxUserIntegrationRecords);
//
//        map.put("code", 0);
//        map.put("data", wxGoods);

        return map;
    }



    public synchronized String getNumber(List<String> list) {
        Random random = new Random();
        int i = random.nextInt(list.size());
        //得到随机号码
        String number = list.get(i);
        WxGoods wxGoods = wxGoodsMapper.get(number);

        int touch = wxGoods.getGoodsTouch();
        //查看号码重置次数是否为0
        if (touch <= 0) {
            int total = wxGoods.getGoodsTotal();
            //减少商品数量
            //查看数量 不足时循环
            if (total == 0) {
                return getNumber(list);
            }
            //数量-1
            //重置次数等于概率

            wxGoodsMapper.setGoods(wxGoods);
            //返回号码
            return number;
        } else {
            //减去重置次数
            //重新运算
            wxGoodsMapper.setRate(wxGoods);

            return getNumber(list);

        }
    }

    @RequestMapping("/createGoods")
    @ResponseBody
    public Map<String, Object> createGoods(String money, HttpServletRequest request) {
        wxGoodsRecordService.createGoodsRecord("123456","15",money);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", 0);
        return map;
    }


    @RequestMapping("/getGoods")
    @ResponseBody
    public Map<String, Object> getGoods(String token, HttpServletRequest request) {
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
        Map<String, Object> goodsRecord = wxGoodsRecordMapper.getGoodsRecord(wxUserInfo.getId());
        Map<String, Object> map = new HashMap<>();
        if(goodsRecord!=null){
            map.put("code", 0);
            if(goodsRecord.get("integration").equals(0)){
                map.put("code", 500);
            }

            map.put("data", goodsRecord);
        }else{
            map.put("code", 510);
            map.put("data", "还未产生中奖商品");
        }
        return map;
    }

    @RequestMapping("/receiveGoods")
    @ResponseBody
    public Map<String, Object> receiveGoods(String token, String id, HttpServletRequest request) throws WxPayException {
        Map<String, Object> map = new HashMap<>();
        WxGoodsRecord wxGoodsRecord = wxGoodsRecordMapper.get(id);
        if (wxGoodsRecord.getStatus() == 0) {
            BigDecimal amount = new BigDecimal(wxGoodsRecord.getWxGoods().getIntegration()).multiply(new BigDecimal(100));
            //可以领取
            if(amount.intValue() >0){
                EntPayService entPayService = payService.getEntPayService();
                EntPayRequest entPayRequest = new EntPayRequest();
                entPayRequest.setPartnerTradeNo(wxGoodsRecord.getOrderNumber());
                entPayRequest.setOpenid(wxGoodsRecord.getWxUser().getOpenid());
                entPayRequest.setCheckName("NO_CHECK");
                entPayRequest.setAmount(amount.intValue());
                entPayRequest.setDescription("幺久送彩头，净化你我他");
                entPayRequest.setSpbillCreateIp("127.0.0.1");
                EntPayResult entPayResult = entPayService.entPay(entPayRequest);
                //判断是否发送成功
                if(!this.checkResult(entPayResult)){
                    map.put("code", 500);
                    map.put("data", "金额发放异常,请稍后领取!");
                    return map;
                }
            }

            wxGoodsRecord.setStatus(1);
            wxGoodsRecordMapper.update(wxGoodsRecord);
            map.put("code", 0);
            map.put("data", "领取成功!");
        } else {
            map.put("code", 500);
            map.put("data", "已领取!");
        }
        return map;
    }

    /**
     * 转盘页面
     *
     * @return
     */
    @RequestMapping("/testRedPack")
    @ResponseBody
    public Map<String, Object> testRedPack( HttpServletRequest request) throws WxPayException {
        Map<String, Object> map = new HashMap<>();
        EntPayService entPayService = payService.getEntPayService();
        EntPayRequest entPayRequest = new EntPayRequest();
        entPayRequest.setPartnerTradeNo("sdf45ds64f56ds45f6");
        entPayRequest.setOpenid("oWwr_0AkSD1gQR-bFsHIIZgRp37A");
        entPayRequest.setCheckName("NO_CHECK");
        entPayRequest.setAmount(11);
        entPayRequest.setDescription("幺久送彩头，净化你我他");
        entPayRequest.setSpbillCreateIp("127.0.0.1");
        EntPayResult entPayResult = entPayService.entPay(entPayRequest);
        //判断是否发送成功
        if(!this.checkResult(entPayResult)){
            map.put("code", 500);
            map.put("data", "金额发放异常,请稍后领取!");
            return map;
        }        map.put("code", 0);
        map.put("data", "领取成功!");
        return map;
    }

    private boolean checkResult(EntPayResult entPayResult){
        boolean success = true;
        Map<String, String> map = entPayResult.toMap();
        List<String> successStrings = Lists.newArrayList(WxPayConstants.ResultCode.SUCCESS, "");
        if (!successStrings.contains(StringUtils.trimToEmpty(entPayResult.getReturnCode()).toUpperCase())
                || !successStrings.contains(StringUtils.trimToEmpty(entPayResult.getResultCode()).toUpperCase())) {
            StringBuilder errorMsg = new StringBuilder();
            if (entPayResult.getReturnCode() != null) {
                errorMsg.append("返回代码：").append(entPayResult.getReturnCode());
            }
            if (entPayResult.getReturnMsg() != null) {
                errorMsg.append("，返回信息：").append(entPayResult.getReturnMsg());
            }
            if (entPayResult.getResultCode() != null) {
                errorMsg.append("，结果代码：").append(entPayResult.getResultCode());
            }
            if (entPayResult.getErrCode() != null) {
                errorMsg.append("，错误代码：").append(entPayResult.getErrCode());
            }
            if (entPayResult.getErrCodeDes() != null) {
                errorMsg.append("，错误详情：").append(entPayResult.getErrCodeDes());
            }
            this.getLogger().error("\n结果业务代码异常，返回结果：{},\n{}", map, errorMsg.toString());
            success = false;
        }
        return success;
    }

    protected Logger getLogger() {
        return LoggerFactory.getLogger(this.getClass());
    }
}
